/**
 * created by 江心才子, 2020/6/23
 * Copyright (c) 2020, 270628297@qq.com All Rights Reserved.
 * #                   *********                            #
 * #                  ************                          #
 * #                  *************                         #
 * #                 **  ***********                        #
 * #                ***  ****** *****                       #
 * #                *** *******   ****                      #
 * #               ***  ********** ****                     #
 * #              ****  *********** ****                    #
 * #            *****   ***********  *****                  #
 * #           ******   *** ********   *****                #
 * #           *****   ***   ********   ******              #
 * #          ******   ***  ***********   ******            #
 * #         ******   **** **************  ******           #
 * #        *******  ********************* *******          #
 * #        *******  ******************************         #
 * #       *******  ****** ***************** *******        #
 * #       *******  ****** ****** *********   ******        #
 * #       *******    **  ******   ******     ******        #
 * #       *******        ******    *****     *****         #
 * #        ******        *****     *****     ****          #
 * #         *****        ****      *****     ***           #
 * #          *****       ***        ***      *             #
 * #            **       ****        ****                   #
 */
package com.wyl.keypad

import android.content.Context
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.graphics.drawable.StateListDrawable
import android.util.AttributeSet
import android.util.Log
import android.util.TypedValue
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.core.view.children
import com.wyl.base.utils.dp

/**
 * 项目名称：LearnAndroid_CustomUI
 * 创建人：江心才子
 * 创建时间：2020-06-23 15:02
 * 内容描述：
 * 修改说明：
 */
private const val TAG = "KeyPadView"

class KeyPadView : ViewGroup {
    constructor(context: Context) : super(context) {
        init(context)
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        init(context, attrs)
    }

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        init(context, attrs, defStyleAttr)
    }

    var numberColor = -1
    var numberSize = -1f
    var itemPressColor = -1
    var itemNormalColor = -1

    private fun init(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) {
        initAttrs(context, attrs)
        setupItem()
    }

    private fun setupItem() {
        removeAllViews()
        repeat(11) {
            TextView(context).apply {
                text = if (it == 10) {
                    "删除"
                } else {
                    it.toString()
                }
                gravity = Gravity.CENTER
                setTextSize(TypedValue.COMPLEX_UNIT_PX, numberSize)
                setTextColor(numberColor)
                background = StateListDrawable().apply {
                    addState(
                        intArrayOf(android.R.attr.state_pressed),
                        GradientDrawable().apply {
                            setColor(resources.getColor(R.color.keypad_item_press_color))
                            cornerRadius = 5.dp()
                        }
                    )
                    addState(
                        intArrayOf(),
                        GradientDrawable().apply {
                            setColor(resources.getColor(R.color.keypad_item_color))
                            cornerRadius = 5.dp()
                        }
                    )
                }
                setOnClickListener {
                    Toast.makeText(context, text, Toast.LENGTH_SHORT).show()
                }
                addView(this)
            }
        }
    }

    private fun initAttrs(context: Context, attrs: AttributeSet?) {
        val ta = context.obtainStyledAttributes(attrs, R.styleable.KeyPadView)
        numberColor = ta.getColor(
            R.styleable.KeyPadView_numberColor,
            Color.WHITE
        )
        numberSize = ta.getDimension(R.styleable.KeyPadView_numberSize, 16.dp())
        Log.d(TAG, "numberSize ==> $numberSize")
        itemPressColor = ta.getResourceId(
            R.styleable.KeyPadView_itemPressColor,
            resources.getColor(R.color.keypad_item_press_color)
        )
        itemNormalColor = ta.getResourceId(R.styleable.KeyPadView_itemNormalColor, numberColor)
        ta.recycle()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
//        val widthMode = MeasureSpec.getMode(widthMeasureSpec)
        val widthSize = MeasureSpec.getSize(widthMeasureSpec)
//        val heightMode = MeasureSpec.getMode(heightMeasureSpec)
        val heightSize = MeasureSpec.getSize(heightMeasureSpec)
//        Log.d(TAG, "widthMode = $widthMode")
        Log.d(TAG, "widthSize = $widthSize")
        Log.d(TAG, "heightSize = $heightSize")
        val perItemWidth = widthSize / 3
        val perItemHeight = heightSize / 4

        val normalWidthSpec = MeasureSpec.makeMeasureSpec(perItemWidth, MeasureSpec.EXACTLY)
        val deleteWidthSpec = MeasureSpec.makeMeasureSpec(perItemWidth * 2, MeasureSpec.EXACTLY)
        val heightSpec = MeasureSpec.makeMeasureSpec(perItemHeight, MeasureSpec.EXACTLY)
        MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY)
        children.forEachIndexed { index, view ->
//            measureChild(
//                view,
//                if (index == childCount - 1) deleteWidthSpec else normalWidthSpec,
//                heightSpec
//            )
            view.measure(
                if (index == childCount - 1) deleteWidthSpec else normalWidthSpec,
                heightSpec
            )
        }
        setMeasuredDimension(widthSize, heightSize)
    }

    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
        val item = getChildAt(0)
        item.layout(0, 0, item.measuredWidth, item.measuredHeight)
        Log.d(TAG, "onLayout ==> item.measuredWidth = ${item.measuredWidth}")
        Log.d(TAG, "onLayout ==> item.measuredHeight = ${item.measuredHeight}")

        var left = 0
        var top = 0
        var right = 0
        var bottom = 0
        children.forEachIndexed { _, view ->
            if (right + view.measuredWidth > measuredWidth) {
                //换行
                left = 0
                top = bottom
            } else {
                left = right
            }
            right = left + view.measuredWidth
            bottom = top + view.measuredHeight
            view.layout(left, top, right, bottom)
        }
    }
}